﻿import datetime
import pandas
from xtquant.xtdata import get_trading_dates

def last_trade_day(ref_day: int, market='SH'):
    # 将 int 格式的 20230101 转成 date 对象
    ref_date = datetime.datetime.strptime(str(ref_day), '%Y%m%d').date()

    # 取过去 30 天的交易日列表
    start_date = (ref_date - datetime.timedelta(days=30)).strftime('%Y%m%d')
    end_date   = str(ref_day)
    td_list    = get_trading_dates(market, start_time=start_date, end_time=end_date, count=-1)

    # 毫秒时间戳 -> date
    td_dates = [datetime.datetime.fromtimestamp(ts // 1000).date() for ts in td_list]

    # 返回“最后一个比 ref_date 小的交易日”
    last_day = max(d for d in td_dates if d < ref_date)
    return int(last_day.strftime('%Y%m%d'))  

def gen_targetpos_sk001(capital):
    trade_date = int(datetime.datetime.today().strftime('%Y%m%d'))
    yesterday  = last_trade_day(trade_date)
    print('yesterday=%s, trade_date=%d' % (yesterday, trade_date))

    targetpos = pandas.read_csv(r'D:/prod/sk001/targetpos/%d.csv' % yesterday)  # code,w1000,price

    d = targetpos.copy()
    d['code'] = d['code'].str.replace('XSHG', 'SH').str.replace('XSHE', 'SZ')
    d['targetpos'] = capital * d.w1000 / d.price / d.w1000.sum()
    d['targetpos'] = (d['targetpos'] / 100).round() * 100
    d = d.fillna(0)  # code,targetpos,price
    return d